<template>
	<view class="shelf-box">
		<u-navbar :is-back="false" title="" v-show="!editFlag">
			<view class="read-time">
				<text>{{ tips }}</text>
			</view>
			<view class="slot-wrap">
				<u-icon name="search" size="40" style="margin-right: 20rpx;" @click="handleToSearch"></u-icon>
				<u-icon name="clock" size="40" style="margin-right: 20rpx;" @click="handleToHistory"></u-icon>
				<u-icon name="edit-pen" color="#061B41" size="40" @click="handleToEdit"></u-icon>
			</view>
		</u-navbar>
		<u-navbar :back-text="checkAllFlag?'全选':'取消全选'" back-icon-name="" v-show="editFlag" :custom-back="handleToCheckedAll">
			<view class="edit-wrap">
				<text style="font-size: 30rpx;font-weight: bold;" @click="handleToSave">完成</text>
			</view>
		</u-navbar>
		<view class="bookshelf-content">
			<block v-if="shelfList.length > 0">
				<view class="shelf-list" v-show="!editFlag">
					<view v-for="item in shelfList" :key="item.book_id" @longpress.stop="longpressToEdit(item.book_shelf_id)" @click="handleToRead(item)">
						<shelf-card :name="item.name" :is_over="item.is_over" :index="item.index" :bookId="item.book_id" :chapter_id="item.last_read_chapter"
						 :chapter_count="item.chapter_count" :image="item.image" />
					</view>
					<view>
						<view class="add-book" @click="handleToLibrary">
							<u-icon name="plus" size="60" color="rgb(146, 200, 255)"></u-icon>
						</view>
					</view>
				</view>
				<u-checkbox-group class="shelf-list" @change="checkboxGroupChange" v-show="editFlag" active-color="rgb(146, 200, 255)">
					<u-checkbox class="check-list" v-model="item.checked" v-for="(item, index) in shelfList" :key="index" :name="item.book_shelf_id"
					 shape="circle">
						<shelf-card :name="item.name" :is_over="item.is_over" :index="item.index" :bookId="item.book_id" :chapter_id="item.last_read_chapter"
						 :chapter_count="item.chapter_count" :image="item.image" :opacity="editFlag?.4:1" :isClick="false" />
					</u-checkbox>
				</u-checkbox-group>
			</block>
			<view v-else>
				<u-empty text="您还未添加任何书籍" mode="list"></u-empty>
				<view style="font-size:28rpx;text-align:center;margin-bottom:20rpx"></view>
				<u-button :ripple="true" :custom-style="{background:'#92C8FF',color:'#ffffff'}" @click="handleToLibrary">去书城添加</u-button>
			</view>
		</view>
		<u-modal v-model="deleteShow" :content="content" show-cancel-button @confirm="handleToConfirmDelete"></u-modal>
		<u-toast ref="uToast" />
		<!-- 底部导航 -->
		<tab-bar></tab-bar>

		<view class="detele-bottom" @click="handleToDelete" v-show="editFlag">
			删除所选({{deleteList.length}})
		</view>
	</view>
</template>

<script>
	import {
		mapState
	} from 'vuex'
	export default {
		name: 'shelf',
		data() {
			return {
				editFlag: false,
				checkAllFlag: true,
				loading: false,
				deleteList: [],
				deleteShow: false,
				content: '',
				timeLine: [{
						time: [6, 7, 8, 9],
						tips: ['早上好', '美好的一天开始啦']
					},
					{
						time: [10, 11],
						tips: ['上午好', '又在摸鱼吗']
					},
					{
						time: [12, 13, 14],
						tips: ['中午好', '吃了吗您']
					},
					{
						time: [15, 16, 17],
						tips: ['下午好', '又在摸鱼吗']
					},
					{
						time: [18],
						tips: ['还不吃饭', '要下班啦']
					},
					{
						time: [19, 20, 21, 22],
						tips: ['晚上好', '愉快的晚上开始了']
					},
					{
						time: [23, 24],
						tips: ['晚上好', '夜猫子还不睡觉']
					},
					{
						time: [1, 2],
						tips: ['夜深了', '早点休息吧', '明天不上班?']
					}
				]
			}
		},
		watch: {
			shelfList(val) {
				if (val.length == 0) {
					this.editFlag = false;
				}
				uni.redirectTo({
					url: '/pages/shelf/index',
					animationType: 'none'
				})
			},
			deleteList(nVal, oVal) {
				if (nVal.length === 0) {
					this.checkAllFlag = true;
				} else {
					if (nVal.length === this.shelfList.length) {
						this.checkAllFlag = false;
					} else {
						this.checkAllFlag = true;
					}
				}
			},
			editFlag(val) {
				if (!val) {
					this.shelfList.map(val => {
						val.checked = false;
					});
					this.deleteList = []
				}
			}
		},
		computed: {
			...mapState({
				iStatusBarHeight: state => state.global.iStatusBarHeight,
				token: state => state.global.token,
				shelfList: state => state.shelf.shelfList,
				name: state => state.global.name || '游客'
			}),
			tips() {
				const currentHours = new Date().getHours()
				const currentTips = this.timeLine.find(item => item.time.includes(currentHours))
				if (currentTips && currentTips.tips.length > 0) return `${this.getRandomTip(currentTips.tips)},${this.name}`
				return `您好,${this.name}`
			}
		},
		onShow() {
			this.handleGetBookShelf()
		},
		onUnload() {
			this.editFlag = false
		},
		onPullDownRefresh() {
			this.$store.dispatch('updateShelfList').then(res => {
				this.$refs.uToast.show({
					title: '刷新成功',
					type: 'success',
					position: 'top'
				});
				uni.stopPullDownRefresh()
			})
		},
		onBackPress(event) {
			if (this.editFlag) {
				this.editFlag = false
				return true;
			}
		},
		methods: {
			// 获取书架数据
			async handleGetBookShelf() {
				try {
					if (!this.token) {
						uni.showModal({
							title: '提示',
							content: '您还未登录,登陆后可以添加书籍到书架!',
							confirmText: '去登陆',
							success: function(res) {
								if (res.confirm) {
									uni.navigateTo({
										url: '/pages/center/login'
									})
								}
							}
						});
						return
					}
					uni.showLoading({
						title: '加载中'
					})
					await this.$store.dispatch('updateShelfList')
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
				}
			},
			handleToRead(item) {
				uni.navigateTo({
					url: `/pages/read/index?bookId=${item.book_id}&chapterId=${item.last_read_chapter}`,
				});
			},
			// 去搜索页
			handleToSearch() {
				uni.navigateTo({
					url: `/pages/search/index`
				});
			},
			// 去书城
			handleToLibrary() {
				uni.switchTab({
					url: `/pages/home/index`
				});
			},
			// 去阅读历史
			handleToHistory() {
				uni.navigateTo({
					url: `/pages/history/index`
				});
			},
			// 编辑书架
			handleToEdit() {
				if (this.shelfList.length === 0) {
					this.$refs.uToast.show({
						title: '书架还是空空的呢',
						type: 'warning',
						position: 'top'
					})
					return;
				}
				this.editFlag = !this.editFlag;
			},
			// 长按编辑
			longpressToEdit(id) {
				uni.vibrateShort({
					success: () => {
						if (!this.editFlag) {
							this.shelfList.forEach(item => {
								if (item.book_shelf_id == id) {
									item.checked = true;
									this.deleteList.push(item.book_shelf_id)
								}
							})
							this.editFlag = !this.editFlag;
						}
					}
				});
			},
			checkboxGroupChange(e) {
				this.deleteList = e;
			},
			// 全选
			handleToCheckedAll() {
				let _deleteList = [];
				this.shelfList.map(val => {
					val.checked = this.checkAllFlag;
				});
				if (this.checkAllFlag) {
					this.shelfList.forEach(item => {
						_deleteList.push(item.book_shelf_id)
					});
				}
				this.checkAllFlag = !this.checkAllFlag;
				this.deleteList = _deleteList;
			},
			// 删除
			handleToDelete() {
				if (this.deleteList.length === 0) {
					this.$refs.uToast.show({
						title: '您未选择任何书籍',
						type: 'warning'
					})
				} else {
					this.content = `您确定要删除这${this.deleteList.length}本书籍吗`;
					this.deleteShow = true;
				}
			},
			// 确认删除
			async handleToConfirmDelete() {
				if (this.token) {
					let bookShelfId = this.deleteList.join(',');
					await this.$store.dispatch('delBookFromShelf', bookShelfId)
					this.$refs.uToast.show({
						title: `成功删除${this.deleteList.length}本书籍`,
						type: 'success',
						position: 'top'
					})
					this.deleteList = [];
					await this.$store.dispatch('updateShelfList')
				}
			},
			// 保存
			handleToSave() {
				if (this.editFlag) {
					this.editFlag = false;
					this.checkAllFlag = true;
					this.shelfList.map(val => {
						val.checked = false;
					});
					this.deleteList = [];
				}
			},
			getRandomTip(tips) {
				return tips[Number(Math.random() * (tips.length - 1)).toFixed(0)]
			}

		}
	}
</script>

<style lang="scss" scoped>
	.shelf-box {
		background: #F5F8FC;
		min-height: 100vh;

		.load {
			position: fixed;
			top: 0;
			left: 0;
			height: 100vh;
			width: 100vw;
			display: flex;
			align-items: center;
			justify-content: center;
			background: white;
			z-index: 100;
		}

		.read-time {
			display: flex;
			justify-content: flex-start;
			align-items: center;
			padding: 0 20px;
			width: 60%;
			font-size: 34rpx;
		}

		.slot-wrap {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			width: 40%;
			padding: 0 20px;
		}

		.edit-wrap {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			width: 100%;
			padding: 0 20px;
		}

		.box-header {
			border-radius: 0 0 40rpx 40rpx;
			background: #F5F8FC;

			.box-title {
				display: flex;
				justify-content: space-between;
				padding: 32rpx 32rpx 0rpx 32rpx;
				margin-bottom: 10rpx;
				font-family: Alibaba PuHuiTi;

				text {
					font-size: 40rpx;
					font-weight: 800;
					color: rgba(6, 27, 65, 1);
					opacity: 0.75;
				}
			}

			.top-bar {
				padding: 40rpx 32rpx 20rpx 32rpx;
				background: #F5F8FC;

				.search-box {
					display: flex;
				}
			}

		}


		.bookshelf-content {
			margin: 20rpx;
			padding: 36rpx 32rpx;
			background: rgba(255, 255, 255, 1);
			border-radius: 12rpx;

			.shelf-list {
				display: grid;
				grid-template-columns: 33.33% 33.33% 33.33%;
				grid-auto-flow: row dense;
				justify-items: center;
			}

			.add-book {
				display: flex;
				align-items: center;
				justify-content: center;
				height: 240rpx;
				width: 182rpx;
				background-color: #c9d6df;
				border-radius: 12rpx;
			}

			.bookshelf-timecount {
				border-bottom: 1rpx solid rgba(6, 27, 65, 0.08);
				padding-bottom: 28rpx;
				margin-bottom: 40rpx;

				.timecount-top {
					font-size: 30rpx;
					font-family: Alibaba PuHuiTi;
					font-weight: 600;
					color: rgba(6, 27, 65, 0.75);
					margin-bottom: 46rpx;
					display: flex;
					justify-content: space-between;
					align-items: flex-start;

					.top-title {}

					.edit-button {
						.delete {
							margin-right: 10rpx;
						}

						.save {}
					}
				}
			}
		}

		.detele-bottom {
			position: fixed;
			bottom: 0;
			left: 0;
			width: 90vw;
			text-align: center;
			padding: 24rpx 32rpx;
			background: white;
			border-radius: 12rpx;
			margin: 0 5vw 40rpx 5vw;
			z-index: 10;
		}
	}

	.check-list {
		position: relative;
		line-height: initial;

		::v-deep.u-checkbox__icon-wrap {
			position: absolute;
			top: 20rpx;
			right: 32rpx;
			z-index: 2;
		}

		::v-deep.u-checkbox__label {
			margin: 0;
		}
	}
</style>
